package com.ms.p2p.controller.admin;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.content.Link;
import com.ms.p2p.plugin.validation.annotation.PermissionValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.LinkProvider;
import com.ms.p2p.utils.JsonDataGridHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 友情链接
 */
@Controller("AdminLinkController")
@RequestMapping("/admin/link")
public class AdminLinkController extends AdminBaseController {

	@Reference
	private LinkProvider linkProvider;

	@Validations(perms = { @PermissionValidator(permission = "link:add") })
	@RequestMapping("/add")
	public String add(HttpServletRequest request, @RequestParam(value = "id", required = false) Integer id) {
		if (id != null) {
			Link link = linkProvider.getOne(id);
			request.setAttribute("link", link);
		}
		return "admin/link/edit";
	}

	@Validations(perms = { @PermissionValidator(permission = "link:edit") })
	@RequestMapping("/edit")
	@ResponseBody
	public Message edit(HttpServletRequest request, HttpSession session, Link link)
			throws IllegalAccessException, InvocationTargetException, IntrospectionException {
		String message = "";
		if (link.getId() == null) {
			linkProvider.insert(link);
		} else {
			linkProvider.update(link);
		}
		return Message.success("操作成功");
	}

	@Validations(perms = { @PermissionValidator(permission = "link:del") })
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(@RequestParam(value = "id") Integer id) {
		linkProvider.del(id);
		return Message.success("删除成功");
	}
	@RequestMapping(value = {"/queryData"}, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public PageBean queryData(HttpServletRequest request, HttpSession session
							 , PageBean page
	) {
		List<Link> linklist = linkProvider.getList();
		page.setList(linklist);
		page.setTotalCount(linklist.size());
		return JsonDataGridHelper.createJSONData(page);
	}
	@RequestMapping("/list")
	public String list(HttpServletRequest request, HttpSession session) {
		return "admin/link/list";
	}

	@Override
	public boolean getBinderFlag() {
		return false;
	}
}
